import axios from "axios";
import store from "@/store";
// import { getToken } from "@/utils/auth";
import { MessageBox, Message } from "element-ui";

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  withCredentials: false, // send cookies when cross-domain requests
  timeout: 0, // request timeout
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    // var token = getToken();
    // if (token) {
    //   config.headers.AccessToken = getToken();
    // }
    return config;
  },
  (error) => {
    // do something with request error
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const res = response.data;
    // if the custom code is not 200, it is judged as an error.
    return res;
  },
  (error) => {
    // 转404
    // const res = response.data;
    const { response } = error;
    if (response && response.data.code === 40011) {
      // 登录超时,请重新登录
      MessageBox.confirm("登录超时", "请重新登录", {
        confirmButtonText: "重新登录", //"重新登录"
        cancelButtonText: "取消", //"取消",
        type: "warning",
      }).then(() => {
        store.dispatch("user/resetToken").then(() => {
          location.reload();
        });
      });
    } else if (error.message == "已取消") {
      Message.closeAll();
      Message({
        // message: error.msg || error.message,
        message: error.msg || error.message,
        type: "info",
        duration: 5 * 1000,
      });
      return;
    } else {
      Message.closeAll();
      Message({
        // message: error.msg || error.message,
        message: error.msg || error.message,
        type: "error",
        duration: 5 * 1000,
      });
      return;
    }
  }
);

export default service;
